%eyelink2_blink_remover


clear;
clc;
close all;

scnsize = get(0,'ScreenSize');

redraw=0;
files = dir('*.eye'); % find all files with the eye extention
% data_list entries must be 8 characters long.(eyelink2 still lives in dos)
if length(files)==0
    disp(' ');
    disp('there are no *.eye files in current directory');
    cd;
    return
end
files.name;

for fp_num=1:length(files)
	file_name=files(fp_num).name;
	file_name(end-3:end)=[]
%     file_name='ian01';
	file_name(file_name==' ')=[];
	eye_file=[file_name '.eye'];
	mat_file=[file_name '.mat'];
	load(mat_file );
	fp = fopen(eye_file);
	if fp==-1
		error(['can not open ' eye_file]);
	end
	rdata=fscanf(fp,'%f',[1,inf]);
	fclose(fp);
	data=reshape(rdata,4,floor(length(rdata)/4))';
	clear rdata
	
	time=data(data(:,1)>0,1);
	x   =data(data(:,1)>0,2);
	y   =data(data(:,1)>0,3);
	size=data(data(:,1)>0,4);
	clear data;
	blink=(size<1)*1;
	blink(end)=0;
	if ~isfield(A,'screenRect')
		A.screenRect=[0 0 1152 864];
	end
	if ~isfield(A,'pixperdeg')
		A.pixperdeg=19;
	end
	eye_time=time-time(1);
	x1   =(x-(A.screenRect(3)/2))/A.pixperdeg;
	y1   =(y-(A.screenRect(4)/2))/A.pixperdeg;
	shrinkage=abs([0;diff(size)]);
	

    vel_x=[0; diff(x1)./(diff(eye_time)/1000)];
	vel_y=[0; diff(y1)./(diff(eye_time)/1000)];
	speed=(sqrt(vel_x.^2+vel_y.^2));
	%speed=smooth3_b(sqrt(vel_x.^2+vel_y.^2));
    if redraw
        fig(50);
        set(50,'Position',[5 (scnsize(4)*.6)+30 scnsize(3)-8 round(scnsize(4)*.3) ],'name',mat_file,'NumberTitle','off');
        clf;cla;hold on;tickout
        set(gca,'Position',[ .05 .11 .9 .81]);
%          plot(eye_time(eye_type>0),eye_x(eye_type>0),'.-');
%         plot(eye_time(eye_type>0),eye_y(eye_type>0),'.-r');
        %%%%%%plot(eye_time,vel_x,'g');
        %%%%%%plot(eye_time,vel_y,'y');
        plot(eye_time,shrinkage,'.-','color',[.5 .5 .5]);
		h_speed=plot(eye_time,speed/10,'.-g');

        plot(eye_time,x1,'.-b');
        plot(eye_time,y1,'.-r');
        plot(eye_time(~~blink),x1(~~blink),'.c');
        plot(eye_time(~~blink),y1(~~blink),'.m');
		axis tight
        hline(50/10);
		ylim([-50 100]);
        h_blink=hplot(eye_time,blink*50);
    end
	%speed2=smooth3_b(speed);
	speed2=speed;
    speed2(find((abs(x1)>40|abs(y1)>40)&speed<50))=100;
    speed2(end)=1; % can't be zero and needs to be less than threshold
    eye_x1=x1;
    eye_y1=y1;
    i=1;
    end_eye=[];
    start_eye=[];
    s_start_eye=[];
    start_blink=[];
    end_blink=[];
	while sum(diff(blink)==1)>0
        start_blink(i)=min(find(diff([0;blink])== 1)); % put a zero on each end to force end of saccade if it goes off the end of the block
        end_blink(i)  =min(find(diff([0;blink])==-1));
        if redraw
            xlim([eye_time(max([1 start_blink(i)-50])) eye_time(min([length(eye_time) end_blink(i)+50]))])
            a=vline(eye_time([start_blink(i) end_blink(i)]),'y');	   
            pause(.2);
        end
        if max(speed(start_blink(i): end_blink(i)))>900		
            [val loc]=max(speed(start_blink(i):end_blink(i)));
            find_max=start_blink(i)+loc-1;		
            speed2(find(speed(start_blink(i):end_blink(i))==0)+start_blink(i)-1)=val;
            speed2(1)=1;% these are set to prevent searches for fixation prior to recording
            speed2(end)=1;% these are set to prevent searches for fixation after recording

            if redraw
                delete(h_speed);
                h_speed=plot(eye_time,speed2/10,'.-g');
            end
            %%%%%%%%%%%%%%min speed limit is set to 15 for london

            min_speed=15;
            p=100;
            min_range=max([1;find_max-p]);
            while all(speed2(min_range:find_max)>min_speed | speed2(min_range:find_max)==0) & min_range>1
                p=p+100;
                min_range=max([1;find_max-p]);
            end
            start_blink2(i)=(max(find(speed2(min_range:find_max)<min_speed & speed2(min_range:find_max)>0))+min_range-1);
            
            p=100;
            max_range=min([end_blink(i)+p length(speed2)]);
            while all(speed2(find_max:max_range)>min_speed | speed2(find_max:max_range)==0) & max_range<length(speed2)
                p=p+100;
                max_range=min([find_max+p length(speed2)]);
            end
            clear p;
            end_blink2(i)=(min(find(speed2(find_max:max_range)<min_speed & speed2(find_max:max_range)>0))+find_max-1);
            
            if redraw
                b=vline(eye_time([start_blink2(i) end_blink2(i)]),'k');
                plot(eye_time(start_blink2(i)),x1(start_blink2(i)),'ob')
                plot(eye_time(start_blink2(i)),y1(start_blink2(i)),'or')
                plot(eye_time(end_blink2(i)),x1(end_blink2(i)),'ob')
                plot(eye_time(end_blink2(i)),y1(end_blink2(i)),'or')
            end
            range=(start_blink2(i):end_blink2(i));
            inc_x=diff(x1([range(1) range(end)]))/(length(range)-1);
            inc_y=diff(y1([range(1) range(end)]))/(length(range)-1);

            
            
            if inc_x
                x1(range)=(x1(range(1)):inc_x:x1(range(end)))';
            else
                x1(range)=x1(range(1));
            end
            if inc_y
                y1(range)=(y1(range(1)):inc_y:y1(range(end)))';
            else
                y1(range)=y1(range(1));
            end
            if redraw
                plot(eye_time(range),x1(range),'ob');
                plot(eye_time(range),y1(range),'or');
            end            
            % check to make sure that there are not two blinks in a row check            
            if blink(min(range(range>4))-3)==6 | blink(min(range(range>4))-3)==4 %check 3 points back
                blink(max(find(diff(blink(1:min(range)))==6))+1:max(range)-1)=1;
                speed2(max(3,min(range)-2):min(range))=100;
            else
                blink(range)=6;
                blink([min(range(range>1))-1 max(range)])=0;
            end
        else
            b=vline(0);
            start_blink2(i)=start_blink(i);
            end_blink2(i)=end_blink(i);

            blink(start_blink(i)+1:end_blink(i))=4;
            blink([start_blink(i) end_blink(i)])=0;
        end
        
        if redraw
            delete(h_blink)
            h_blink=hplot(eye_time,blink*50);     
            fig(51);clf;
            set(51,'Position',[5 (scnsize(4)*.25)+30 scnsize(3)-8 round(scnsize(4)*.3) ],'name',mat_file,'NumberTitle','off');
            clf;cla;hold on;tickout
            subplot('Position',[0.690141 0.0857143 0.299296 0.814286]);hold on;axis square; axis([-20 20 -20 20])
            temp_range=([(max([1 start_blink2(i)-25])):(min([length(eye_time) end_blink2(i)+25]))]);
            plot(eye_x1(temp_range),eye_y1(temp_range),'.-r');
            plot(x1(min(temp_range):end_blink2(i)),y1(min(temp_range):end_blink2(i)),'o-');
            subplot('Position',[0.0334507 0.0761905 0.608275 0.814286]);hold on;
            plot(eye_time(temp_range),eye_x1(temp_range),'.-c')
            plot(eye_time(temp_range),eye_y1(temp_range),'.-m');
            plot(eye_time(min(temp_range):end_blink2(i)),x1(min(temp_range):end_blink2(i)),'.-b')
            plot(eye_time(min(temp_range):end_blink2(i)),y1(min(temp_range):end_blink2(i)),'.-r');
            axis tight; ylim([-30 30])
            fig(50);
            pause(1)
            fig(50); % again in case the user plays with the figs            
            delete(a)
            delete(b)
        end % redraw
        i=i+1;
    end
    if redraw
        axis auto
        ylim([-5 5])
    end % redraw
	
    fig(fp_num);
    set(fp_num,'Position',[5 (scnsize(4)*.6)+30 scnsize(3)-8 round(scnsize(4)*.3) ],'name',mat_file,'NumberTitle','off');
    clf;cla;hold on;tickout
    set(gca,'Position',[ .05 .11 .9 .81]);

    vel_x1=[0;diff(x1)./diff(eye_time/1000)];
    vel_y1=[0;diff(y1)./diff(eye_time/1000)];
    speed1=sqrt(vel_x1.^2+vel_y1.^2);
    %plot(eye_time,vel_x,'g');
    %plot(eye_time,vel_y,'y');
    plot(eye_time,speed1,'.-g');
    plot(eye_time(blink>4),speed1(blink>4),'.y');
    plot(eye_time,x1,'.-b');
    plot(eye_time,y1,'.-r');
    plot(eye_time(blink>4),x1(blink>4),'.c');
    plot(eye_time(blink>4),y1(blink>4),'.m');
    plot(eye_time,blink*10,'k')
    axis tight;ylim([-100 900])
    axis([0 400000 -100 900 ])
    hline(50);
	
    if ~isfield(A,'colors')% just for andrews old data
        A.colors=define_colors;
        A.colors.PRO=A.colors.GREEN;
        A.colors.ANTI=A.colors.RED;
        A.colors.BACKGROUND=A.colors.D_GREY        
    end
	% change the 32 based psychophysics toolbox colors into
	% the 0-1 based stuff for matlab 
	names = fieldnames(A.colors);
	for i=1:length(names)
		colors.(names{i})=A.colors.(names{i})/31;
	end
	
	B=A;
    B.name=file_name;
    B.colors=colors;
    B.eye_x=x1;
    B.eye_x_raw=eye_x1;
    B.eye_y=y1;
    B.eye_y_raw=eye_y1;
    B.vel_x=vel_x1;
    B.vel_y=vel_y1;
    B.speed=speed1;
    B.time=eye_time;
    B.blink=blink;

    save([file_name 'B.mat'],'B')

end

disp('eyelink2_blink_remover')

